

#include "can.h"
#include "can_ringbuff.h"


/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     return can wait transmit data length
*/
int16_t can_ringbuf_read(STR_CAN_BUFFER* packetbuf, STR_CAN_MESSAGE* temp)
{
	uint8_t  message_len = 0;
	uint16_t read_index = packetbuf->read_index;
	STR_CAN_MESSAGE* obj_temp = temp;
	
	if(packetbuf->reading_flg != 1)
	{
		packetbuf->reading_flg = 1;
		
		if((read_index == packetbuf->write_index) && (packetbuf->full_flg == 0))
		{
			packetbuf->reading_flg = 0;
			message_len = 0;
			return message_len;
		}
		
		*obj_temp = packetbuf->msg[read_index];
		
		message_len = 1;
		
		read_index++;
		read_index %= packetbuf->length;
		
		packetbuf->read_index = read_index;
		packetbuf->reading_flg = 0;
		packetbuf->full_flg = 0;
	}
	
	else
	{
		message_len = 0;
	}	
	
	return message_len;
}

/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/
int16_t can_ringbuf_write(STR_CAN_BUFFER* packetbuf, STR_CAN_MESSAGE* temp)
{
	STR_CAN_MESSAGE* obj_temp = temp;
	uint16_t write_index = packetbuf->write_index;
	
	if((packetbuf->full_flg != 1) && (packetbuf->writing_flg != 1))
	{
		packetbuf->writing_flg = 1;
		
		packetbuf->msg[write_index] = *(obj_temp);
		
		write_index++;
		write_index %= packetbuf->length;
		
		if(write_index == packetbuf->read_index)
		{
			packetbuf->full_flg = 1;
			packetbuf->write_index = write_index;
			packetbuf->writing_flg = 0;
			
			return -1;
		}
		
		packetbuf->write_index = write_index;
		packetbuf->writing_flg = 0;
		
		return 1;
	}
	else
	{
		return -1;
	}
	
}

/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

int16_t get_can_ringbuf_space(STR_CAN_BUFFER* packetbuf)
{
	int16_t re_space = 0;
	int16_t index_diff = 0;
	
	if(packetbuf->read_index == packetbuf->write_index)
	{
		re_space = packetbuf->length;
	}
	else if((packetbuf->full_flg) != 1)
	{
		index_diff = (int16_t)(packetbuf->read_index - packetbuf->write_index);
		re_space = (index_diff + packetbuf->length) % packetbuf->length;
	}
	
	return re_space;
}


